import {Button, Form, Input, Modal} from "antd";
import React, {useEffect, useImperativeHandle, useState} from "react";

const EditNote = (props) => {
    const [form] = Form.useForm();
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [title, setTitle] = useState('修改笔记')
    const [currentNote, setCurrentNote] = useState({
        id: '',
        type: '',
        described: '',
        tags: ''
    })
    //用useImperativeHandle暴露一些外部ref能访问的属性
    useImperativeHandle(props.onRef, () => {
        return {
            open: (data)=>{
                setTitle('修改笔记'+data.type)
                setCurrentNote(data)
                form.setFieldsValue(data);
                setIsModalOpen(true)
            },
        };
    });
    const  handleOk = async () => {
        const res = await fetch('/api/notes/updateNotes', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(form.getFieldValue())
        })
        const data = await res.text();
        handleCancel()
    }
    const handleCancel = () => {
        form.resetFields()
        setIsModalOpen(false)
        setCurrentNote({
            id: '',
            type: '',
            described: '',
            tags: ''
        }); // 关闭时重置状态
    }
    return (
        <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Form
                form={form}
                initialValues={{
                    remember: true,
                    ...currentNote
                }}
                autoComplete="off"
            >
                <Form.Item
                    label="类型"
                    name="type"
                    rules={[{ required: true, message: '请输入类型!' }]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="描述"
                    name="described"
                    rules={[{ required: true, message: '请输入描述!' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="标签"
                    name="tags"
                    rules={[{ required: true, message: '请输入标签!' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    )
}

export default EditNote